/*****
 * 
 * This java class is used to decompress the mesowest file (.gz files)downloaded from Utah site
 * 
 */

package com.sjsu.CMPE226.etl.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.GZIPInputStream;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 
 * @author Deepali Pawar
 * 
 */

public class GzipDecompressor {

	protected static Logger decom = LoggerFactory.getLogger("database");

	public void decompress(String source, String dest) {
		try {
			File folder = new File(source);
			File[] listOfFiles = folder.listFiles();
			for (int i = 0; i < listOfFiles.length; i++) {

				if (listOfFiles[i].isFile()) {
					String source1 = source
							+ listOfFiles[i].getName();
					String outFilename = dest + i
							+ ".out";
					System.out.println(source1);
					decom.info("File to be extracted: " + source1);
					FileInputStream instream = new FileInputStream(source1);
					GZIPInputStream ginstream = new GZIPInputStream(instream);
					FileOutputStream outstream = new FileOutputStream(
							outFilename);
					byte[] buf = new byte[1024];
					int len;
					while ((len = ginstream.read(buf)) > 0) {
						outstream.write(buf, 0, len);
					}
					decom.info("********Gzip File Successfylly Extracted********");
					decom.info("Extracted .out file name: " + outFilename);
					
					ginstream.close();
					outstream.close();
				}
				doFile(listOfFiles[i]);
			}
		}

		catch (IOException ioe) {
			ioe.printStackTrace();
		} catch (Exception ex) {
			ex.printStackTrace();

		}
	}
	
	public void doFile(File file) throws IOException {
        file.delete();
        if (file.exists()) {
          throw new IOException("Failed to delete  " + file.getPath());
        }
      }
}